package com.jiac.coderunner.controller;

import com.jiac.coderunner.entity.FieldInfo;
import com.jiac.coderunner.entity.TableInfo;
import com.jiac.coderunner.util.CreateUtils;
import com.jiac.coderunner.util.DBInfo;
import com.jiac.coderunner.util.OutputJson;
import com.jiac.coderunner.util.TemplateInfo;
import freemarker.cache.ClassTemplateLoader;
import freemarker.cache.FileTemplateLoader;
import freemarker.cache.TemplateLoader;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.thymeleaf.util.StringUtils;
import java.io.File;
import java.util.*;

import static com.sun.xml.internal.fastinfoset.alphabet.BuiltInRestrictedAlphabets.table;

@RestController
@RequestMapping("/tpl")
public class TemplateController {

    @RequestMapping("/tables")
    public OutputJson tables(@RequestBody TemplateInfo tplInfo){
        OutputJson opjson = new OutputJson();
        Configuration config = new Configuration(Configuration.VERSION_2_3_23);
        List<TableInfo> tables = tplInfo.getTables();
        String basePackage = tplInfo.getBasePackage();
        String outputFloder = tplInfo.getOutputFloder();

        String fileTypes = tplInfo.getFileTypes();
        boolean standardFloder = tplInfo.isStandardFloder();
        if (StringUtils.isEmpty(basePackage)) {
            opjson.setSuccess(false);
            opjson.setMsg("请设置包名");
            return opjson;
        }
        if (StringUtils.isEmpty(outputFloder)) {
            opjson.setSuccess(false);
            opjson.setMsg("请设置输出路径");
            return opjson;
        }
        if (StringUtils.isEmpty(fileTypes)) {
            opjson.setSuccess(false);
            opjson.setMsg("请选择需要生成的文件类型");
            return opjson;
        }
        try {
            TemplateLoader templateLoader = null;
            String ftlUrl = tplInfo.getFtlFloder();
            File ftlFolder = null;
            if (!StringUtils.isEmpty(ftlUrl)) {
                ftlFolder = new File(ftlUrl);
                if (ftlFolder.exists()) {
                    templateLoader = new FileTemplateLoader(ftlFolder);
                }
            }
            if (templateLoader==null) {
                //templateLoader = new WebappTemplateLoader(context,CreateUtils.defaultFloder);
                templateLoader = new ClassTemplateLoader(this.getClass(),"/ftl");
            }
            config.setTemplateLoader(templateLoader);
        } catch (Exception e) {
            e.printStackTrace();
            opjson.setMsg("设置模板加载器出现异常");
            opjson.setSuccess(false);
            return opjson;
        }
        StringBuffer buffer = new StringBuffer("");
        outputFloder = outputFloder+"/"+basePackage.replace(".","/");
        for (TableInfo table : tables) {
            table.setPackageName(basePackage);
            String[] fileArr = fileTypes.split(",");
            List<String> fileList = Arrays.asList(fileArr);
            List<FieldInfo> fields = DBInfo.getTableCloumns(table.getTableName());

            if (fields.isEmpty()) {
                buffer.append("表:"+table.getTableName()+",未查询到字段");
                continue;
            }
            List<String> impClses = new ArrayList();
            for (FieldInfo field : fields) {
                String impcls = field.getImportCls();
                if (!StringUtils.isEmpty(impcls) && !impClses.contains(impcls)){
                    impClses.add(impcls);
                }
            }
            table.setImpClses(impClses);
            table.setFields(fields);
            Map data = new HashMap();
            data.put("table",table);
            try {
                Template template = null;
                String entityPackage = "";
                if (tplInfo.isStandardFloder()) {
                    entityPackage = basePackage+".entity."+table.getClsName()+"Entity";
                } else {
                    entityPackage = basePackage+"."+table.getClsName()+"Entity";
                }
                //生成实体
                if (fileList.contains("entity")) {
                    if (tplInfo.isStandardFloder()) {
                        table.setPackageName(basePackage+".entity");
                    }
                    //创建模板
                    template = config.getTemplate("entity.ftl","UTF-8");
                    CreateUtils.generateFile(template,outputFloder,data,"Entity.java",standardFloder);
                }
                //生成Dao层
                if (fileList.contains("dao")) {
                    table.getImpClses().add(entityPackage);
                    if (tplInfo.isStandardFloder()) {
                        table.setPackageName(basePackage+".dao");
                    }
                    //创建模板
                    template = config.getTemplate("dao.ftl","UTF-8");
                    CreateUtils.generateFile(template,outputFloder,data,"Dao.java",standardFloder);
                }
                //生成业务层
                if (fileList.contains("service")) {
                    if (!table.getImpClses().contains(entityPackage)) {
                        table.getImpClses().add(entityPackage);
                    }
                    if (tplInfo.isStandardFloder()) {
                        table.setPackageName(basePackage+".service");
                        table.getImpClses().add(basePackage+".dao."+table.getClsName()+"Dao");
                    } else {
                        table.getImpClses().add(basePackage+"."+table.getClsName()+"Dao");
                    }
                    //创建模板
                    template = config.getTemplate("service.ftl","UTF-8");
                    CreateUtils.generateFile(template,outputFloder,data,"ServiceImpl.java",standardFloder);
                }
                //生成控制层
                if (fileList.contains("controller")) {
                    if (!table.getImpClses().contains(entityPackage)) {
                        table.getImpClses().add(entityPackage);
                    }
                    if (tplInfo.isStandardFloder()) {
                        table.setPackageName(basePackage+".controller");
                        table.getImpClses().add(basePackage+".service."+table.getClsName()+"ServiceImpl");
                    } else {
                        table.getImpClses().add(basePackage+"."+table.getClsName()+"ServiceImpl");
                    }
                    //创建模板
                    template = config.getTemplate("controller.ftl","UTF-8");
                    CreateUtils.generateFile(template,outputFloder,data,"Controller.java",standardFloder);
                }
                //生成映射文件
                if (fileList.contains("mapper")) {
                    //创建模板
                    template = config.getTemplate("mapper.ftl","UTF-8");
                    CreateUtils.generateFile(template,outputFloder,data,"Mapper.xml",standardFloder);
                }
                //生成页面
                if (fileList.contains("jsp")) {
                    //创建模板
                    template = config.getTemplate("jsp.ftl","UTF-8");
                    CreateUtils.generateFile(template,outputFloder,data,".jsp",standardFloder);
                }
            } catch (Exception e) {
                e.printStackTrace();
                opjson.setSuccess(false);
                opjson.setMsg("表:"+table.getTableName()+"生成entity出现异常；");
            }
        }
        opjson.setSuccess(true);
        if (StringUtils.isEmpty(buffer.toString())) {
            opjson.setMsg("创建成功");
        } else {
            opjson.setMsg(buffer.toString());

        }
        return opjson;
    }

}
